package com.work.shart.common.exception.handel;

import com.work.shart.common.exception.BizException;
import com.work.shart.common.exception.ExceptionEnum;
import com.work.shart.common.result.Result;
import com.work.shart.common.result.ResultVo;

import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;

import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.text.MessageFormat;

/**
 * 公共异常处理
 * @author cong
 */
@Slf4j
@RestControllerAdvice
public  class GlobalException {

    /**
     * 参数校验异常
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    public ResultVo methodArgumentNotValidException(MethodArgumentNotValidException ex) {
        print("MethodArgumentNotValidException", ExceptionEnum.VALID_PARAM.getMsg(), ex);
        return Result.error(ExceptionEnum.VALID_PARAM.getCode(), ex.getBindingResult().getFieldError().getDefaultMessage());
    }

    // 参数校验异常
    @ExceptionHandler(IllegalArgumentException.class)
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    public ResultVo illegalArgumentException(IllegalArgumentException ex) {
        print("IllegalArgumentException", ExceptionEnum.VALID_PARAM.getMsg(), ex);
        return Result.error(ExceptionEnum.VALID_PARAM.getCode(), ex.getMessage());
    }

    /**
     * 通用业务异常
     *
     * @param exception
     * @return
     */
    @ExceptionHandler(value = BizException.class)
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    public ResultVo bizException(BizException exception) {
        print("BizException", ExceptionEnum.BIZ_RUNTIME.getMsg(), exception);
        return Result.error(ExceptionEnum.BIZ_RUNTIME.getCode(), exception.getMessage());
    }


    protected void print(String exceptionName, String enumMsg, Exception e) {
        String str = MessageFormat.format("{0}-[{1}] :", exceptionName, enumMsg);
        log.warn(str, e);
    }

}
